package streaming.func.udf;

import streaming.api.beans.SensorReading;
import streaming.func.model.HashCode;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

/**
 * 标量函数 (Scalar Functions)
 */
public class UDFTest1_scalar {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        DataStream<String> inputStream = env.readTextFile("D:\\IdeaProjects\\springboot-flink-1\\flinkTutorial\\src\\main\\resources\\sensor.txt");
        DataStream<SensorReading> dataStream = inputStream.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0],new Long(fields[1]), new Double(fields[2]));
        });
        Table sensorTable = tableEnv.fromDataStream(dataStream);

        // 1.自定义标量函数，实现求id的hash值
        HashCode hashCode = new HashCode(23);
        // 2. 注册UDF
        tableEnv.registerFunction("hashCode", hashCode);
        // 3. table API
        Table resultTable = sensorTable.select("id, temperature, hashCode(id)");
        // 4.
        tableEnv.createTemporaryView("sensor", sensorTable);
        Table resultSqlTable = tableEnv.sqlQuery("select id, temperature , hashCode(id) from sensor");
        // 打印输出
        tableEnv.toAppendStream(resultTable, Row.class).print();
        tableEnv.toAppendStream(resultSqlTable, Row.class).print();

        env.execute();
    }
}
